#include "server.h"
#include <gxgfunc.h>

#define CLIENTMAX 10

int exitPipe[2];

void sigFunc(int signum) {
    printf("signum = %d\n", signum);
    write(exitPipe[1], "1", 1);
    printf("Parent process is going to die!\n");
}

int main(int argc, char* argv[]) {
    //./server 10.21.55.5 1234 3
    ARGS_CHECK(argc, 4);

    pipe(exitPipe);
    if (fork() != 0) {
        //主进程
        close(exitPipe[0]);
        signal(SIGUSR1, sigFunc);
        wait(NULL);
        exit(0);
    }

    //子进程
    close(exitPipe[1]);

    int workerNum = atoi(argv[3]);

    threadPool_t threadPool;
    threadPoolInit(&threadPool, workerNum);
    makeWorker(&threadPool);
    int sockFd;
    tcpInit(&sockFd, argv[1], argv[2]);

    int msgLength = 0;
    char msgBuf[BUFFERSIZE] = {0};

    int epfd = epoll_create(1);
    epollAdd(sockFd, epfd);
    epollAdd(exitPipe[0], epfd);

    /*客户端数组，存放客户端的netFd*/
    int clients[CLIENTMAX] = {0};
    int clientNum = 0;

    struct epoll_event readyArr[10];
    while (1) {
        int readyNum = epoll_wait(epfd, readyArr, 10, -1);
        printf("epoll_wait returns.\n");
        for (int i = 0; i < readyNum; i++) {
            if (readyArr[i].data.fd == sockFd) {
                //接收连接
                int netFd = accept(sockFd, NULL, NULL);

                //先接收账户信息，尝试登录
                recvn(netFd, &msgLength, sizeof(int));
                recvn(netFd, msgBuf, msgLength);
                puts(msgBuf);

                //把netFd加入到客户端数组并监听
                clients[clientNum] = netFd;
                epollAdd(clients[clientNum], epfd);
                ++clientNum;

                if (0) {
                    pthread_mutex_lock(&threadPool.taskQueue.mutex);
                    taskEnqueue(&threadPool.taskQueue, netFd);
                    printf("New task!\n");
                    pthread_cond_signal(&threadPool.taskQueue.cond);
                    pthread_mutex_unlock(&threadPool.taskQueue.mutex);
                }

            } else if (readyArr[i].data.fd == exitPipe[0]) {
                printf("child process, threadPool is going to die.\n");

                threadPool.exitFlag = 1;
                pthread_cond_broadcast(&threadPool.taskQueue.cond);

                for (int j = 0; j < workerNum; j++) {
                    pthread_join(threadPool.tid[j], NULL);
                }
                pthread_exit(NULL);
            } else {
                //监听客户端netFd
                for (int j = 0; j < clientNum; j++) {
                    if (readyArr[i].data.fd == clients[j]) {
                        recvn(clients[j], &msgLength, sizeof(int));
                        recvn(clients[j], msgBuf, msgLength);
                        puts(msgBuf);
                    }
                }
            }
        }
    }

    return 0;
}